package com.gok.service.impl;

import com.gok.server.dao.UserMapper;
import com.gok.server.pojo.User;
import com.gok.service.UserService;
import com.gok.util.MapAndObjectUtil;
import com.gok.util.RedisUtil;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author: Administrator
 * @create time: 2020/12/23 09:05
 * @description:
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public List<User> findAllUser() {
        //查询出所有用户信息
        List<User> users = userMapper.selectAll();

        MapAndObjectUtil<User> mapAndObjectUtil = new MapAndObjectUtil<User>();

        if(!CollectionUtils.isEmpty(users)){
            //遍历每个对象

            users.forEach(user -> {
                //将user对象转为map集合，然后存到redis缓存中去
                redisUtil.hmset(user.getUsername(),mapAndObjectUtil.toMap(user));
            });
        }

        //模拟取出数据---一个例子
        Map map = redisUtil.hmget(users.get(0).getUsername());
        System.out.println("redis的数据： "+map);

        User u = null;
        try {
            //取出的map转为一个对象
            u = mapAndObjectUtil.toObject(map,User.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("user: "+u);

        return users;
    }

    @Override
    public int findLogin(User user) {
        //通过用户名，获取缓存中的map集合
        Map map=redisUtil.hmget(user.getUsername());

        MapAndObjectUtil<User> mapAndObjectUtil = new MapAndObjectUtil<User>();

        //将获取的map集合转换为对象
        try{
            User fictitious=mapAndObjectUtil.toObject(map,User.class);
            //判断缓存中
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return 0;
    }
}
